package com.tjetc.controller;

import com.tjetc.common.CodeUtil;
import com.tjetc.common.JsonResult;
import com.tjetc.entity.Admin;
import com.tjetc.entity.Merchant;
import com.tjetc.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("admin")
public class AdminLoginController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private CodeUtil codeUtil;

    // 登录接口
    @RequestMapping("login")
    public JsonResult adminLogin(Admin admin,
                                 @RequestParam("code") String code,
                                        HttpSession session) {
        String session_code = (String) session.getAttribute("code");
        // 首先检查验证码是否正确(不区分大小写)
        if(!session_code.equalsIgnoreCase(code)) {
            return new JsonResult<>(1, "验证码不正确", null);
        }
        JsonResult result = adminService.login(admin);
        if (result.getState() == 0) {
            session.setAttribute("admin", ((Admin) result.getData()).getId());
        }
        return result;
    }

    // 用于获取验证码
    @RequestMapping("get")
    public JsonResult handleCode(HttpSession session) throws Exception {
        String code = codeUtil.generateCaptcha();
        session.setAttribute("code", code);
        return new JsonResult<>(0, "", codeUtil.generateCaptchaImage(code));
    }

    @RequestMapping("logout") // 用于获取验证码
    public JsonResult logout(HttpSession session) throws Exception {
        session.removeAttribute("admin");
        return new JsonResult<>(0, "", true);
    }
}